<?php

namespace app\controller\notify;


use app\exception\NotifyException;
use app\libs\DianDianPaySDK\action\PaymentApi;
use app\model\Notify;
use app\model\Orders;
use think\helper\Arr;
use think\helper\Str;
use think\Request;

class NotifyDianDianPay implements NotifyInterface
{
    public function notify(Request $request)
    {
        $data = $request->param('data',[]);
        if(empty($data)) throw new NotifyException("data required");
        $orderId = Arr::get($data,'metadata.order_id',0);
        $order = Orders::findOrEmpty($orderId);
        if($order->isEmpty()) throw new NotifyException("order not exists");
        if($order->order_status == Orders::ORDER_STATUS_COMPLETED) throw new NotifyException("order has payed",$order);
        $result_code = Arr::get($data,'result.result_code','');
        $tradeNo = Arr::get($data,'id');
        $orderNo = Arr::get($data,'merchant_order_id');
        $merchantNo = Str::startsWith($orderNo,'#') ? $orderNo : sprintf('#%s',$orderNo);
        $orderAmount = Arr::get($data,'amount',0);
        $orderAmount = $orderAmount > 0 ? bcdiv($orderAmount,'100',2) : '0.00';
        $isChange = false;
        //交易号缺失
        if(empty($order->trade_no)) {
            $order->trade_no = $tradeNo;
            $isChange = true;
        }
        //商户号缺失
        if(empty($order->order_no))  {
            $order->order_no = $merchantNo;
            $isChange = true;
        }
        //订单金额不对的问题,修正
        if($orderAmount > 0 && $orderAmount != $order->total_price){
            $order->total_price = $orderAmount;
            $order->tax_total = bcsub($orderAmount,$order->sub_total,2);
            $isChange = true;
        }
        if($isChange) $order->save();
        if($result_code == "SUCCEEDED"){
            Orders::completed($order,$result_code,$tradeNo,$merchantNo);
        }else{
            //失败
            $exception = Arr::get($data,'result.result_message','');
            throw new NotifyException($exception,$order);
        }
        return $order;
    }


    //重定向问题
    public function capture(Request $request,Orders $order)
    {
        //获取详情
        $api = new PaymentApi($order->payment);
        $config = $order->payment->config;
        $body = [
            'merchant_id'=>Arr::get($config,'merchant_no'),
            'merchant_order_id'=>$order->order_no,
            'id'=>$order->trade_no,
        ];
        $response = $api->query_result($body);
        Notify::saveParams($order->id,['params'=>$body,'response'=>$response],Notify::TYPE_PAYPAL_DETAIL);
        $orderStatus = Arr::get($response,'data.order.payment_status','');
        $result_status = Arr::get($response,'data.result.result_status','');
        $isPaysuccess = $orderStatus == 'succeeded' && $result_status == "S";
        if(!$isPaysuccess) throw new \Exception("diandian pay fail");
    }

}